<template>
  <div class="app-container brand-page">
    <div class="toolbar">
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入商品品牌"
        class="filter-input"
        clearable
        @keyup.enter.native="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <div class="toolbar-right">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
          >添加品牌</el-button
        >
        <el-button @click="handleBatchToggle(1)">批量开启</el-button>
        <el-button @click="handleBatchToggle(0)">批量关闭</el-button>
      </div>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="品牌图片" width="160">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.logo"
            :src="scope.row.logo"
            fit="cover"
            class="brand-logo"
          />
          <span v-else class="text-muted">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="品牌名称" min-width="180" />
      <el-table-column label="启用状态" width="160">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.showStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
          <span class="status-text">{{
            scope.row.showStatus ? "开启" : "关闭"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            class="danger-text"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :current-page="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="520px"
      @close="handleDialogClose"
    >
      <el-form
        ref="brandFormRef"
        :model="brandForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="brandForm.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logo">
          <div class="logo-uploader">
            <el-upload
              class="upload-box"
              action="/api/merchant/upload/image"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeLogoUpload"
            >
              <div v-if="brandForm.logo" class="logo-preview">
                <img :src="brandForm.logo" alt="logo" />
                <el-button
                  type="text"
                  size="mini"
                  @click.stop.prevent="brandForm.logo = ''"
                  >移除</el-button
                >
              </div>
              <div v-else class="placeholder">
                <i class="el-icon-plus"></i>
                <p>上传图片</p>
              </div>
            </el-upload>
            <div class="upload-hint">建议尺寸 240x240，支持 JPG/PNG</div>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="brandForm.showStatus"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="status-text">{{
            brandForm.showStatus ? "开启" : "关闭"
          }}</span>
        </el-form-item>
        <el-form-item label="品牌描述">
          <el-input
            v-model="brandForm.brandStory"
            type="textarea"
            :rows="3"
            placeholder="请输入品牌介绍"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBrands,
  createBrand,
  updateBrand,
  deleteBrand,
  updateBrandShowStatus,
  getBrand
} from "@/api/product";
import { getToken } from "@/utils/auth";

export default {
  name: "GoodsBrand",
  data() {
    return {
      listQuery: {
        keyword: "",
        pageNum: 1,
        pageSize: 10
      },
      listLoading: false,
      list: [],
      total: 0,
      multipleSelection: [],
      dialogVisible: false,
      dialogTitle: "添加品牌",
      brandForm: this.getDefaultBrandForm(),
      rules: {
        name: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
        logo: [{ required: true, message: "请上传品牌LOGO", trigger: "change" }]
      }
    };
  },
  computed: {
    uploadHeaders() {
      return {
        Authorization: getToken()
      };
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getDefaultBrandForm() {
      return {
        id: null,
        name: "",
        logo: "",
        showStatus: 1,
        brandStory: ""
      };
    },
    async getList() {
      this.listLoading = true;
      try {
        const params = {
          keyword: this.listQuery.keyword,
          pageNum: this.listQuery.pageNum,
          pageSize: this.listQuery.pageSize
        };
        const response = await getBrands(params);
        const data = response.data || {};
        const rawList = data.list || data.data || [];
        this.list = rawList.map(item => ({
          ...item,
          showStatus:
            (item.showStatus !== undefined
              ? item.showStatus
              : item.enabled !== undefined
              ? item.enabled
              : item.status !== undefined
              ? item.status
              : 1) || 0
        }));
        this.total = data.total || data.count || rawList.length;
      } catch (error) {
        console.error(error);
      } finally {
        this.listLoading = false;
      }
    },
    handleSearch() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handlePageChange(page) {
      this.listQuery.pageNum = page;
      this.getList();
    },
    handleAdd() {
      this.dialogTitle = "添加品牌";
      this.brandForm = this.getDefaultBrandForm();
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.brandFormRef && this.$refs.brandFormRef.clearValidate();
      });
    },
    async handleEdit(row) {
      this.dialogTitle = "编辑品牌";
      try {
        const response = await getBrand(row.id);
        const data = response.data || row;
        this.brandForm = {
          id: data.id,
          name: data.name,
          logo: data.logo,
          showStatus:
            data.showStatus !== undefined
              ? data.showStatus
              : data.enabled !== undefined
              ? data.enabled
              : 1,
          brandStory: data.brandStory || data.desc || ""
        };
      } catch (error) {
        this.brandForm = {
          id: row.id,
          name: row.name,
          logo: row.logo,
          showStatus: row.showStatus,
          brandStory: row.brandStory || ""
        };
      } finally {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.brandFormRef && this.$refs.brandFormRef.clearValidate();
        });
      }
    },
    handleDialogClose() {
      this.$refs.brandFormRef && this.$refs.brandFormRef.clearValidate();
    },
    handleLogoSuccess(response) {
      if (response && response.code === 200) {
        this.brandForm.logo = response.data.url;
        this.$message.success("上传成功");
      } else {
        this.$message.error(response.message || "上传失败");
      }
    },
    beforeLogoUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error("只能上传图片文件");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB");
      }
      return isImage && isLt2M;
    },
    handleDialogConfirm() {
      this.$refs.brandFormRef.validate(async valid => {
        if (!valid) return;
        const payload = {
          name: this.brandForm.name,
          logo: this.brandForm.logo,
          showStatus: this.brandForm.showStatus,
          brandStory: this.brandForm.brandStory
        };
        try {
          if (this.brandForm.id) {
            await updateBrand(this.brandForm.id, payload);
            this.$message.success("品牌更新成功");
          } else {
            await createBrand(payload);
            this.$message.success("品牌创建成功");
          }
          this.dialogVisible = false;
          this.getList();
        } catch (error) {
          console.error(error);
        }
      });
    },
    handleDelete(row) {
      this.$confirm(`确认删除品牌【${row.name}】吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await deleteBrand(row.id);
          this.$message.success("删除成功");
          this.getList();
        })
        .catch(() => {});
    },
    async handleStatusChange(row) {
      try {
        await updateBrandShowStatus({
          ids: [row.id],
          showStatus: row.showStatus
        });
        this.$message.success("状态更新成功");
      } catch (error) {
        row.showStatus = row.showStatus === 1 ? 0 : 1;
      }
    },
    handleBatchToggle(status) {
      if (!this.multipleSelection.length) {
        this.$message.warning("请先选择要操作的品牌");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id);
      this.$confirm(
        `确认将选中的 ${ids.length} 个品牌${
          status === 1 ? "开启" : "关闭"
        }吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          await updateBrandShowStatus({ ids, showStatus: status });
          this.$message.success("批量操作成功");
          this.getList();
        })
        .catch(() => {});
    }
  }
};
</script>

<style scoped>
.brand-page {
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.filter-input {
  width: 260px;
  margin-right: 12px;
}

.toolbar-right {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.brand-logo {
  width: 120px;
  height: 60px;
  border-radius: 4px;
  object-fit: contain;
  background: #f5f7fa;
  border: 1px solid #ebeef5;
}

.status-text {
  margin-left: 8px;
  color: #606266;
}

.danger-text {
  color: #f56c6c;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.logo-uploader .upload-box {
  width: 160px;
  height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.logo-uploader .placeholder {
  text-align: center;
  color: #909399;
}

.logo-preview img {
  width: 120px;
  height: 120px;
  object-fit: contain;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 6px;
}

.text-muted {
  color: #c0c4cc;
}
</style>
